// index.js
// 获取应用实例
const app = getApp()
import WxValidate from "../../utils/WxValidate"
import customerApi from '../../api/customer'
Page({
  data: {
    phone:'',
    name:"",
    wxValidate:{},
    address:"",
    areaCode:'',
    region:[],
    addressId:"",
    detailAddress:"",
    addressName:""//所在区域

  },
  onLoad() {
     //初始化验证参数
     this.initValidate()
     this.getAddressData()
  },
  getAddressData() {
    let formData = {
      method:'GET'
    }
    customerApi.customerAddress(formData).then((res)=>{
      let data = res
      if(data) {
        this.setData({
          phone:data.phone,
          name:data.name,
          areaCode:data.provinceCode?[data.provinceCode,data.cityCode,data.countyCode]:null,
          addressName:data.province + data.city + data.county,
          region:[data.provinceCode,data.cityCode,data.countyCode],
          addressId :data.id,
          detailAddress :data.detailAddress
        })
     
      }
    })
  },
  initValidate() {
    const rules = {
       phone: {
        required: true,
        tel:true
      },
      name: {
        required: true,
      },
      addressName:{
        required: true,
      },
      detailAddress:{
        required: true,
      }
    }
    const messages = {
      name: {
        required: '请输入姓名'
      },
      phone: {
        required: "请输入手机号码"
      },
      addressName: {
        required: '请选择所在区域'
      },
      detailAddress: {
        required: '请输入详细地址'
      }
    }
    this.wxValidate = new WxValidate(rules, messages)
  
  },
  submitBtn(e) {
    console.log("---submitBtn-->",e.detail.value,this.data.addressId)
    if (!this.wxValidate.checkForm(e.detail.value)) {
      const error = this.wxValidate.errorList[0]
      wx.showToast({
        title: error.msg,
        icon: "none",
        duration: 800
      })
      return 
    }
    let formData = {
      data:{
        ...e.detail.value,
        id: this.data.addressId,
        address:this.data.areaCode
      },
      method:'POST'
    }
    customerApi.customerAddress(formData).then(()=>{
      wx.showToast({
        title: this.data.addressId?'修改成功':'新增成功',
        icon: "none",
        duration: 800
      })
    })
    
  },
  bindRegionChange(e) {
    let areaList = e.detail.value
    let areaCodeList =  e.detail.code
    let areaCode = areaCodeList
    let addressName = areaList[0]+areaList[1]+ areaList[2]
    this.setData({areaCode,addressName})
    console.log('picker发送选择改变，携带值为', e.detail)
  },

})
